package com.spider.im.common.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class OpenApiConfig {

    // 从配置文件中读取 OpenAPI 的基本信息
    @Value("${openapi.version:3.0.2}")
    private String openApiVersion;

    @Value("${openapi.info.title:Spider IM Service API}")
    private String apiTitle;

    @Value("${openapi.info.version:1.0-SNAPSHOT}")
    private String apiVersion;

    @Value("${openapi.info.description:API documentation for Spider IM Service}")
    private String apiDescription;

    @Value("${openapi.paths.public:/api/**}")
    private String publicPaths;

    @Value("#{'${openapi.groups:public,admin}'.split(',')}")
    private  List<String> groupNames;

    @Value("#{'${openapi.paths:/api/**,/admin/**}'.split(',')}")
    private List<String> paths;


    /**
     * 配置公共分组的 GroupedOpenApi
     */
    @Bean
    public GroupedOpenApi publicApi() {
        try {
            return GroupedOpenApi.builder()
                    .group("public")
                    .pathsToMatch(publicPaths)
                    .build();
        } catch (Exception e) {
            // 记录异常日志，防止应用因配置错误而崩溃
            throw new RuntimeException("Failed to initialize public GroupedOpenApi", e);
        }
    }

    /**
     * 动态生成其他分组的 GroupedOpenApi（可选扩展）
     * 示例：根据配置文件中的 key-value 动态生成分组
     */
    @Bean
    public List<GroupedOpenApi> dynamicApis() {

        List<GroupedOpenApi> groupedApis = new ArrayList<>();
        if (groupNames.size() != paths.size()) {
            throw new IllegalArgumentException("The number of groups and paths must match");
        }

        for (int i = 0; i < groupNames.size(); i++) {
            groupedApis.add(GroupedOpenApi.builder()
                    .group(groupNames.get(i))
                    .pathsToMatch(paths.get(i))
                    .build());
        }

        return groupedApis;
    }

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("社交平台 API")
                        .version("1.0.0")
                        .description("Description of my API")
                        .termsOfService("https://example.com/terms")
                        .contact(new Contact()
                                .name("API Support")
                                .email("support@example.com")
                                .url("https://example.com/contact"))
                        .license(new io.swagger.v3.oas.models.info.License()
                                .name("Apache 2.0")
                                .url("https://www.apache.org/licenses/LICENSE-2.0.html")));
    }
//
//    @Bean
//    public OpenAPI customOpenAPI() {
//        return new OpenAPI()
//                .info(new Info().title("Your API Title")
//                        .description("Your API Description"))
//                .addSecurityItem(new SecurityRequirement().addList("BearerAuth"))
//                .components(new io.swagger.v3.oas.models.Components()
//                        .addSecuritySchemes("BearerAuth",
//                                new SecurityScheme()
//                                        .type(SecurityScheme.Type.HTTP)
//                                        .scheme("bearer")
//                                        .bearerFormat("JWT")));
//    }
}
